package com.higgins.lawapp.client.maintenance.components;

import java.util.Iterator;
import java.util.List;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.higgins.lawapp.client.maintenance.model.DataItemModel;
import com.higgins.lawapp.client.settings.dataItemModel.DataItemLevelDTO;
import com.higgins.lawapp.client.settings.dataItemModel.DataItemSourceDTO;

public class DataItemSourceListBox extends LayoutPanel implements ChangeHandler	{
	private DataSourceDeleteButton deleteButton;
	private ListBox listBox = new ListBox();
	private List<DataItemSourceDTO> dataItemSourceDTOs;
	private DataItemLevelListBox listBoxChild;
	private FlexTable flexTableChild;
	private DataItemModel dataItemModel;
	
	public DataItemSourceListBox(DataItemModel dataItemModel, DataItemLevelListBox listBoxChild)	{
		this.dataItemModel = dataItemModel;
		this.listBoxChild = listBoxChild;
		setWidth("800px");
		setHeight("25px");

		deleteButton = new DataSourceDeleteButton(dataItemModel);		
		listBox.addChangeHandler(this);
		clearList();
		
		deleteButton.setTitle("Delete DataSource");
		deleteButton.setText("Delete DataSource");
		add(listBox);
		add(deleteButton);
	    setWidgetLeftWidth(listBox, 0, Unit.PCT, 80, Unit.PCT);
	    setWidgetRightWidth(deleteButton, 0, Unit.PCT, 20, Unit.PCT);
	}
	
	public void setDataItemSourceDTOs(List<DataItemSourceDTO> dataItemSourceDTOs)	{
		this.dataItemSourceDTOs = dataItemSourceDTOs;

		clearList();
		addDataItemSourceNamesToList(dataItemSourceDTOs);
	}

	@Override
	public void onChange(ChangeEvent event) {
		dataItemModel.setDataItemSourceSeleced(getSelectedDataItemSourceDTO());
		listBoxChild.setDataItemSourceSeleced(getSelectedDataItemSourceDTO());
	}
	
	// NEW METHOD!!!
	private DataItemSourceDTO getSelectedDataItemSourceDTO()	{
		DataItemSourceDTO dataItemSourceDTO = null;
		if (listBox.getSelectedIndex() > 0)	{
			int dataItemSourceListBoxIndex = listBox.getSelectedIndex() - 1;
			dataItemSourceDTO = dataItemSourceDTOs.get(dataItemSourceListBoxIndex);
		}
		return dataItemSourceDTO ;
	}
	
	private void addDataItemSourceNamesToList(List<DataItemSourceDTO> dataItemSourceDTOs)	{
		if (dataItemSourceDTOs!=null)	{
			Iterator<DataItemSourceDTO> iterator = dataItemSourceDTOs.iterator();
			while (iterator.hasNext())	{
				DataItemSourceDTO dataItemSourceDTO = iterator.next();
				listBox.addItem(dataItemSourceDTO.getDataItemSourceName());
			}
		}
	}
	
	private void clearList()	{
		listBox.clear();
		listBox.addItem("None");
		listBox.setSelectedIndex(0);
	}
}
